﻿namespace mVids
{
    using MediaPortal.Configuration;
    using MediaPortal.Dialogs;
    using MediaPortal.GUI.Library;
    using MediaPortal.Player;
    using MediaPortal.Playlists;
    using MediaPortal.Profile;
    using myLog;
    using Randomness;
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Drawing;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Threading;
    using Action = MediaPortal.GUI.Library.Action;

    public class mvid : GUIWindow, ISetupForm
    {
        private bool alwaysPlayAll;
        private string basePath = "";
        [SkinControl(5)]
        protected GUITextScrollUpControl bioLabel = null;
        [SkinControl(4)]
        protected GUIButtonControl btnPlaylist = null;
        [SkinControl(3)]
        protected GUIButtonControl buttonTwo = null;
        private string currPath = "";
        private bool cycleViews;
        private mVids.database db = new mVids.database();
        [SkinControl(7)]
        protected GUIButtonControl dbviewButton = null;
        private List<string> exts = new List<string>();
        [SkinControl(50)]
        protected GUIFacadeControl facade = null;
        [SkinControl(0x31)]
        protected GUIImage fanArt = null;
        private List<string> fanArtImages = new List<string>();
        private string ffmpegpath = "";
        private int lastItem = 0;
        [SkinControl(110)]
        protected GUIImage mosaic = null;
        private int mosaicHeight;
        private int mosaicWidth;
        private viewMode mVidsCurrView = viewMode.Artists;
        private PlayListPlayer plp = PlayListPlayer.SingletonPlayer;
        private bool showNewIndicator;
        [SkinControl(0x65)]
        protected GUIImage star1 = null;
        [SkinControl(0x66)]
        protected GUIImage star2 = null;
        [SkinControl(0x67)]
        protected GUIImage star3 = null;
        [SkinControl(0x68)]
        protected GUIImage star4 = null;
        [SkinControl(0x69)]
        protected GUIImage star5 = null;
        private bool summaryBio;
        private string thumbdir = "";
        private bool top100Fanart;
        private bool topLevelFanart;
        private List<mVids.musicVideo> videos = new List<mVids.musicVideo>();

        private void addToPlaylist(GUIListItem listItem, bool playNow)
        {
          PlayList playlist = plp.GetPlaylist(PlayListType.PLAYLIST_MUSIC_VIDEO);
          PlayListItem item = new PlayListItem(listItem.Label, listItem.Path, listItem.Duration / 0x3e8);
          plp.CurrentPlaylistType = PlayListType.PLAYLIST_MUSIC_VIDEO;
          playlist.Add(item);
          if (playNow)
          {
            mVids.musicVideo video = new mVids.musicVideo();
            if (facade.ListLayout.ListItems[0].Label == "..")
            {
              video = this.videos[facade.ListLayout.ListItems.IndexOf(listItem) - 1];
            }
            else
            {
              video = this.videos[facade.ListLayout.ListItems.IndexOf(listItem)];
            }
            this.plp.Play(0);
            GUIGraphicsContext.IsFullScreenVideo = true; 
            GUIWindowManager.ActivateWindow(0x7d5);
          }
        }

        private void addToPlaylist(List<GUIListItem> items, bool playNow)
        {
          PlayList playlist = plp.GetPlaylist(PlayListType.PLAYLIST_MUSIC_VIDEO);
            foreach (GUIListItem item in items)
            {
                PlayListItem item2 = new PlayListItem(item.Label, item.Path, item.Duration / 0x3e8);
                playlist.Add(item2);
            }
            this.plp.CurrentPlaylistType = PlayListType.PLAYLIST_MUSIC_VIDEO;
            if (playNow)
            {
                mVids.musicVideo video = new mVids.musicVideo();
                
                if (facade.ListLayout.ListItems[0].Label == "..")
                {
                    video = this.videos[this.facade.ListLayout.ListItems.IndexOf(items[0]) - 1];
                }
                else
                {
                    video = this.videos[this.facade.ListLayout.ListItems.IndexOf(items[0])];
                }
                this.plp.Play(0);
                GUIGraphicsContext.IsFullScreenVideo = true; 
                GUIWindowManager.ActivateWindow(0x7d5);
            }
        }

        private void addToPlaylist(List<mVids.musicVideo> items, bool playNow, bool clear)
        {
            PlayList playlist = plp.GetPlaylist(PlayListType.PLAYLIST_MUSIC_VIDEO);;
            if (clear)
            {
                playlist.Clear();
            }
            foreach (mVids.musicVideo video in items)
            {
                PlayListItem item = new PlayListItem(video.Label, video.Path, video.Duration / 0x3e8);
                playlist.Add(item);
            }
            this.plp.CurrentPlaylistType = PlayListType.PLAYLIST_MUSIC_VIDEO;
            if (playNow)
            {
                this.plp.Play(0);
                GUIGraphicsContext.IsFullScreenVideo = true; 
                GUIWindowManager.ActivateWindow(0x7d5);
            }
        }

        private void addToPlaylistNext(GUIListItem listItem)
        {
            PlayList playlist = plp.GetPlaylist(PlayListType.PLAYLIST_MUSIC_VIDEO);;
            PlayListItem item = new PlayListItem(listItem.Label, listItem.Path, listItem.Duration / 0x3e8);
            this.plp.CurrentPlaylistType = PlayListType.PLAYLIST_MUSIC_VIDEO;
            playlist.Insert(item, this.plp.CurrentSong);
        }

        public string Author()
        {
            return "jburnette";
        }

        public bool CanEnable()
        {
            return true;
        }

        public bool DefaultEnabled()
        {
            return true;
        }

        public string Description()
        {
            return "Organize music videos.";
        }

        private void displayFanart(string artist)
        {
            myLog.logger.log("entered displayFanart");
            if (!((this.mVidsCurrView != viewMode.Top100) || this.top100Fanart))
            {
                this.fanArt.IsVisible = false;
                myLog.logger.log("top100fanart==false");
            }
            else if (!((this.mVidsCurrView != viewMode.Key) || this.top100Fanart))
            {
                this.fanArt.IsVisible = false;
                myLog.logger.log("top100fanart==false");
            }
            else
            {
                try
                {
                    myLog.logger.log("checking for fanart memoryimage of " + artist);
                    if (this.fanArtImages.Contains(artist))
                    {
                        myLog.logger.log("fanart loading for " + artist);
                        this.fanArt.IsVisible = true;
                        this.fanArt.FileName = "[" + artist + "]";
                    }
                    else
                    {
                        this.fanArt.IsVisible = false;
                    }
                }
                catch
                {
                    Log.Error("Music Video DB - Error loading fanart", new object[0]);
                }
            }
        }

        private void doRating(string requestedRating)
        {
            List<string> list;
            if ((this.mVidsCurrView == viewMode.Key) || (this.mVidsCurrView == viewMode.Top100))
            {
                this.db.setRating(this.facade.SelectedListItem.Path, int.Parse(requestedRating));
                list = this.db.getRankings();
                this.videos[this.facade.ListLayout.ListItems.IndexOf(this.facade.SelectedListItem)].rating = requestedRating;
                int num = list.IndexOf(this.facade.SelectedListItem.Path) + 1;
                this.videos[this.facade.ListLayout.ListItems.IndexOf(this.facade.SelectedListItem)].ranking = num.ToString() + " / " + list.Count.ToString();
                this.videoSelected_handler(this.facade.SelectedListItem, this.facade);
            }
            else
            {
                this.db.setRating(this.facade.SelectedListItem.Path, int.Parse(requestedRating));
                list = this.db.getRankings();
                this.videos[this.facade.ListLayout.ListItems.IndexOf(this.facade.SelectedListItem) - 1].rating = requestedRating;
                this.videos[this.facade.ListLayout.ListItems.IndexOf(this.facade.SelectedListItem) - 1].ranking = ((list.IndexOf(this.facade.SelectedListItem.Path) + 1)).ToString() + " / " + list.Count.ToString();
                this.videoSelected_handler(this.facade.SelectedListItem, this.facade);
            }
            if (this.mVidsCurrView == viewMode.Top100)
            {
                this.updateTop100Order();
            }
        }

        private List<string> ExamineDir(string strDir)
        {
            string str2;
            List<string> list = new List<string>();
            string[] files = Directory.GetFiles(strDir);
            int length = files.Length;
            Log.Debug("examine count " + length.ToString(), new object[0]);
            foreach (string str in files)
            {
                str2 = str.Substring(str.LastIndexOf("."));
                Log.Debug("examine file " + str, new object[0]);
                if (this.exts.Contains(str2))
                {
                    Log.Info(str.ToString(), new object[0]);
                    list.Add(str.ToString());
                }
            }
            foreach (string str3 in Directory.GetDirectories(strDir))
            {
                Log.Debug("looking in " + strDir, new object[0]);
                Log.Debug("strdirname " + str3, new object[0]);
                files = Directory.GetFiles(str3);
                Log.Debug("examine count " + files.Length.ToString(), new object[0]);
                foreach (string str in files)
                {
                    str2 = str.Substring(str.LastIndexOf("."));
                    Log.Debug("examine file " + str, new object[0]);
                    if (this.exts.Contains(str2))
                    {
                        Log.Debug(str.ToString(), new object[0]);
                        list.Add(str.ToString());
                    }
                }
                this.ExamineDir(str3);
            }
            return list;
        }

        private void g_Player_PlayBackEnded(g_Player.MediaType type, string filename)
        {
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += new DoWorkEventHandler(this.incPlaycountBGW);
            ArrayList argument = new ArrayList();
            argument.Add(type);
            argument.Add(filename);
            worker.RunWorkerAsync(argument);
        }

        private void g_Player_PlayBackStarted(g_Player.MediaType type, string filename)
        {
            if (type == 0)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(this.setPlaybackInfo), filename);
            }
        }

        public bool GetHome(out string strButtonText, out string strButtonImage, out string strButtonImageFocus, out string strPictureImage)
        {
            Settings settings = new Settings(Config.GetFolder(Config.Dir.Config) + "/MediaPortal.xml", true);
            string str = settings.GetValue("mvid", "displayedname");
            settings.Dispose();
            if (str.Length < 1)
            {
                str = "Music Video DB";
            }
            strButtonText = str;
            strButtonImage = "hover_mVids.png";
            strButtonImageFocus = "hover_mVids.png";
            strPictureImage = "hover_mVids.png";
            return true;
        }

        public int GetWindowId()
        {
            return 0x19df;
        }

        public bool HasSetup()
        {
            return true;
        }

        private void incPlaycountBGW(object sender, DoWorkEventArgs e)
        {
            ArrayList argument = (ArrayList) e.Argument;
            if ((((g_Player.MediaType) argument[0]) == null) && this.db.fileInDB(argument[1].ToString()))
            {
                this.db.incPlayCount(argument[1].ToString());
            }
        }

        public override bool Init()
        {
            if (File.Exists(Config.GetFolder(Config.Dir.Log) + @"\mVids.log"))
            {
                File.Delete(Config.GetFolder(Config.Dir.Log) + @"\mVids.log");
            }
            Settings settings = new Settings(Config.GetFolder(Config.Dir.Config) + "/MediaPortal.xml", false);
            string str = settings.GetValue("mvid", "displayedname");
            if (str.Length < 1)
            {
                str = "Music Video DB";
            }
            GUIPropertyManager.SetProperty("#mvids.displayedname", str);
            string[] strArray = settings.GetValue("mvid", "basepath").Split("|".ToCharArray());
            string str2 = settings.GetValue("movies", "extensions");
            this.exts.AddRange(str2.Split(",".ToCharArray()));
            foreach (string str3 in strArray)
            {
                if (Directory.Exists(str3))
                {
                    FileSystemWatcher watcher = new FileSystemWatcher(str3);
                    watcher.Renamed += new RenamedEventHandler(this.watcher_Renamed);
                    watcher.Created += new FileSystemEventHandler(this.watcher_Created);
                    watcher.Deleted += new FileSystemEventHandler(this.watcher_Deleted);
                    watcher.IncludeSubdirectories = true;
                    watcher.EnableRaisingEvents = true;
                    Log.Info("Music Video DB - Watching for changes in folder {0}", new object[] { str3 });
                }
            }
            this.thumbdir = Config.GetFolder(Config.Dir.Thumbs);
            if (!Directory.Exists(this.thumbdir + @"\mvids"))
            {
                Directory.CreateDirectory(this.thumbdir + @"\mvids");
            }
            this.thumbdir = this.thumbdir + @"\mvids";
            this.basePath = settings.GetValue("mvid", "basepath");
            this.ffmpegpath = settings.GetValue("mvid", "ffmpeg");
            this.cycleViews = settings.GetValueAsBool("mvid", "cycleviews", true);
            this.alwaysPlayAll = settings.GetValueAsBool("mvid", "autoqueueall", true);
            this.showNewIndicator = settings.GetValueAsBool("mvid", "shownewindicator", true);
            this.topLevelFanart = settings.GetValueAsBool("mvid", "toplevelfanart", true);
            this.top100Fanart = settings.GetValueAsBool("mvid", "top100keyfanart", true);
            if (settings.GetValue("mvid", "displayedbio") != "Summary")
            {
                this.summaryBio = false;
            }
            else
            {
                this.summaryBio = true;
            }
            string s = settings.GetValue("mvid", "mosaicsizeheight");
            if (s == "")
            {
                s = "100";
            }
            this.mosaicHeight = int.Parse(s);
            s = settings.GetValue("mvid", "mosaicsizewidth");
            if (s == "")
            {
                s = "75";
            }
            this.mosaicWidth = int.Parse(s);
            settings.Dispose();
            g_Player.PlayBackEnded += new g_Player.EndedHandler(g_Player_PlayBackEnded);
            g_Player.PlayBackStarted += new g_Player.StartedHandler(g_Player_PlayBackStarted);
            return this.Load(GUIGraphicsContext.Skin + @"\mvids.xml");
        }

        private void loadArtists()
        {
            this.mosaic.IsVisible = false;
            GUIPropertyManager.SetProperty("#mvids.hierarchy", "Artists");
            this.showStars(0);
            Settings settings = new Settings(Config.GetFolder(Config.Dir.Config) + "/MediaPortal.xml", true);
            settings.SetValue("mvid", "lastView", "artist");
            settings.SetValue("mvid", "lastSubview", "root");
            settings.Dispose();
            List<mVids.artist> list = new List<mVids.artist>();
            if (this.summaryBio)
            {
                list = this.db.getArtistsAndBios(true);
            }
            else
            {
                list = this.db.getArtistsAndBios(false);
            }
            List<mVids.musicVideo> state = new List<mVids.musicVideo>();
            foreach (mVids.artist artist in list)
            {
                mVids.musicVideo video = new mVids.musicVideo {
                    artist = artist.artistName
                };
                state.Add(video);
            }
            if (state.Count > 0)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(this.loadFanart), state);
            }
            this.facade.Clear();
            for (int i = 0; i < list.Count; i++)
            {
                GUIListItem item = new GUIListItem();
                item.Label = list[i].artistName;
                item.ThumbnailImage = thumbdir + @"\Artists\" + list[i].artistName + ".jpg";
                item.TVTag = list[i].bio;
                item.Duration = list[i].vidCount;
                item.DVDLabel = list[i].tags;
                item.AlbumInfoTag = list[i].averageRating.ToString();
                item.IsFolder = true;
                item.OnItemSelected += new GUIListItem.ItemSelectedHandler(topview_OnItemSelected);
                this.facade.Add(item);
            }
            if (this.facade.Count > 0)
            {
                this.topview_OnItemSelected(facade.ListLayout.ListItems[0], this.facade);
            }
        }

        private void loadFanart(object vids)
        {
            List<mVids.musicVideo> list = (List<mVids.musicVideo>) vids;
            if (Directory.Exists(this.thumbdir + @"\FanArt\"))
            {
                foreach (mVids.musicVideo video in list)
                {
                    try
                    {
                        string[] files = Directory.GetFiles(this.thumbdir + @"\FanArt\", video.artist + "*");
                        if (!(this.fanArtImages.Contains(video.artist) || (files.Length <= 0)))
                        {
                            myLog.logger.log("fanart found for " + video.artist);
                            this.fanArtImages.Add(video.artist);
                            Random random = new Random(Environment.TickCount);
                            Image image = Image.FromFile(files[random.Next(0, files.Length - 1)]);
                            GUITextureManager.LoadFromMemory(image, "[" + video.artist + "]", 0L, image.Width, image.Height);
                        }
                    }
                    catch (Exception exception)
                    {
                        Log.Error("Music Video DB - Error loading fanart for {0}", new object[] { video.artist });
                        Log.Error(exception.ToString(), new object[0]);
                    }
                }
            }
        }

        private void loadTags()
        {
            this.mosaic.IsVisible = true;
            Settings settings = new Settings(Config.GetFolder(Config.Dir.Config) + "/MediaPortal.xml", true);
            settings.SetValue("mvid", "lastView", "tag");
            settings.SetValue("mvid", "lastSubview", "root");
            settings.Dispose();
            this.showStars(0);
            List<string> list = this.db.getTags();
            GUIPropertyManager.SetProperty("#mvids.hierarchy", "Tags");
            this.facade.Clear();
            for (int i = 0; i < list.Count; i++)
            {
                GUIListItem item = new GUIListItem();
                item.Label = list[i];
                List<string> list2 = this.db.getArtistsByTag(list[i]);
                StringBuilder builder = new StringBuilder();
                foreach (string str in list2)
                {
                    builder.AppendLine(str);
                }
                item.TVTag = builder.ToString();
                item.IsFolder = true;
                item.OnItemSelected += new GUIListItem.ItemSelectedHandler(topview_OnItemSelected);
                this.facade.Add(item);
            }
        }

        public override void OnAction(Action action)
        {
            Action.ActionType wID = action.wID;
            if (wID == Action.ActionType.ACTION_PREVIOUS_MENU)
            {
                if (facade.ListLayout.ListItems[0].Label == "..")
                {
                    switch (this.mVidsCurrView)
                    {
                        case viewMode.Artists:
                            this.loadArtists();
                            this.facade.SelectedListItemIndex = lastItem;
                            return;

                        case viewMode.Tag:
                            this.loadTags();
                            this.facade.SelectedListItemIndex = lastItem;
                            return;

                        case viewMode.Top100:
                        case viewMode.Key:
                            return;

                        case viewMode.Similar:
                        {
                            Settings settings2 = new Settings(Config.GetFolder(Config.Dir.Config) + "/MediaPortal.xml", true);
                            string lastView = settings2.GetValue("mvid", "lastView");
                            string lastSubview = settings2.GetValue("mvid", "lastSubview");
                            settings2.Dispose();
                            this.setupLastView(lastView, lastSubview);
                            return;
                        }
                    }
                }
                else
                {
                    base.OnAction(action);
                }
            }
            else if (wID == Action.ActionType.ACTION_KEY_PRESSED)
            {
                switch (((char) action.m_key.KeyChar))
                {
                    case '1':
                        if (!(this.facade.SelectedListItem.IsFolder || !(this.facade.SelectedListItem.Label != "..")))
                        {
                            this.doRating("1");
                        }
                        return;

                    case '2':
                        if (!(this.facade.SelectedListItem.IsFolder || !(this.facade.SelectedListItem.Label != "..")))
                        {
                            this.doRating("2");
                        }
                        return;

                    case '3':
                        if (!(this.facade.SelectedListItem.IsFolder || !(this.facade.SelectedListItem.Label != "..")))
                        {
                            this.doRating("3");
                        }
                        return;

                    case '4':
                        if (!(this.facade.SelectedListItem.IsFolder || !(this.facade.SelectedListItem.Label != "..")))
                        {
                            this.doRating("4");
                        }
                        return;

                    case '5':
                        if (!(this.facade.SelectedListItem.IsFolder || !(this.facade.SelectedListItem.Label != "..")))
                        {
                            this.doRating("5");
                        }
                        return;
                }
            }
            else if (wID != Action.ActionType.ACTION_CONTEXT_MENU)
            {
                base.OnAction(action);
            }
            else
            {
              GUIDialogMenu window = (GUIDialogMenu)GUIWindowManager.GetWindow(0x7dc);
                window.Reset();
                window.SetHeading(GUIPropertyManager.GetProperty("#mvids.displayedname") + " - Context Menu");
                if ((this.facade.Count > 0) && !this.facade.SelectedListItem.IsFolder)
                {
                    window.Add("Add to playlist");
                    window.Add("Add all to playlist");
                    if (plp.GetPlaylist(PlayListType.PLAYLIST_MUSIC_VIDEO).Count != 0)
                    {
                        window.Add("Add to Playlist as next item");
                    }
                    window.Add("Show videos from similar artists");
                }
                window.Add("Force Rescan");
                window.Add("Adjust Random Settings");
                window.DoModal(GUIWindowManager.ActiveWindow);
                string str3 = window.SelectedLabelText;
                if (str3 != null)
                {
                    if (!(str3 == "Add to Playlist"))
                    {
                        if (str3 == "Add all to Playlist")
                        {
                            List<GUIListItem> items = new List<GUIListItem>();
                            items.AddRange(this.facade.ListLayout.ListItems);
                            if (items[0].Label == "..")
                            {
                                items.RemoveAt(0);
                            }
                            if (plp.GetPlaylist(PlayListType.PLAYLIST_MUSIC_VIDEO).Count == 0)
                            {
                                this.addToPlaylist(items, true);
                            }
                            else
                            {
                                this.addToPlaylist(items, false);
                            }
                        }
                        else if (str3 == "Add to Playlist as Next item")
                        {
                            if (this.facade.SelectedListItem.Label != "..")
                            {
                                this.addToPlaylistNext(this.facade.SelectedListItem);
                            }
                        }
                        else if (str3 == "Force Rescan")
                        {
                            BackgroundWorker worker = new BackgroundWorker();
                            worker.DoWork += new DoWorkEventHandler(this.rsWorker_DoWork);
                            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(this.rsWorker_RunWorkerCompleted);
                            worker.RunWorkerAsync();
                        }
                        else if (str3 == "Show Similar Videos")
                        {
                            this.setupSimilarView(this.videos[this.facade.SelectedListItemIndex].artist);
                        }
                        else if (str3 == "Adjust Random Settings")
                        {
                            new Randomness.settings().ShowSettingsDialog();
                        }
                    }
                    else if (this.facade.SelectedListItem.Label != "..")
                    {
                        if (plp.GetPlaylist(PlayListType.PLAYLIST_MUSIC_VIDEO).Count == 0)
                        {
                            this.addToPlaylist(this.facade.SelectedListItem, true);
                        }
                        else
                        {
                            this.addToPlaylist(this.facade.SelectedListItem, false);
                        }
                    }
                }
            }
        }

        protected override void OnClicked(int controlId, GUIControl control, Action.ActionType actionType)
        {
            if (control == this.buttonTwo)
            {
                this.playRandomMenu();
            }
            else if (control == this.dbviewButton)
            {
                if (this.cycleViews)
                {
                    switch (this.mVidsCurrView)
                    {
                        case viewMode.Artists:
                            this.mVidsCurrView = viewMode.Tag;
                            this.dbviewButton.Label = "Tag View";
                            this.loadTags();
                            this.topview_OnItemSelected(facade.ListLayout.ListItems[0], this.facade);
                            goto Label_05ED;

                        case viewMode.Tag:
                            this.mVidsCurrView = viewMode.Top100;
                            this.dbviewButton.Label = "Top 100";
                            this.setupTop100View();
                            this.topview_OnItemSelected(facade.ListLayout.ListItems[0], this.facade);
                            goto Label_05ED;

                        case viewMode.Top100:
                            this.mVidsCurrView = viewMode.Key;
                            this.dbviewButton.Label = "Recent View";
                            this.setupKeyView();
                            this.topview_OnItemSelected(facade.ListLayout.ListItems[0], this.facade);
                            goto Label_05ED;

                        case viewMode.Key:
                            this.mVidsCurrView = viewMode.Artists;
                            this.dbviewButton.Label = "Artist View";
                            this.loadArtists();
                            this.topview_OnItemSelected(facade.ListLayout.ListItems[0], this.facade);
                            goto Label_05ED;
                    }
                }
                else
                {
                    GUIDialogSelect2 window = (GUIDialogSelect2)GUIWindowManager.GetWindow(0x7d9);
                    window.Reset();
                    window.SetHeading("Choose View");
                    window.Add("Artist View");
                    window.Add("Recent View");
                    window.Add("Top 100");
                    window.Add("Tag View");
                    window.DoModal(GUIWindowManager.ActiveWindow);
                    switch (window.SelectedLabel)
                    {
                        case 0:
                            this.mVidsCurrView = viewMode.Artists;
                            this.loadArtists();
                            this.dbviewButton.Focus = false;
                            this.facade.Focus = true;
                            this.topview_OnItemSelected(facade.ListLayout.ListItems[0], this.facade);
                            goto Label_05ED;

                        case 1:
                            this.mVidsCurrView = viewMode.Key;
                            this.setupKeyView();
                            this.dbviewButton.Focus = false;
                            this.facade.Focus = true;
                            this.topview_OnItemSelected(facade.ListLayout.ListItems[0], this.facade);
                            goto Label_05ED;

                        case 2:
                            this.mVidsCurrView = viewMode.Top100;
                            this.setupTop100View();
                            this.dbviewButton.Focus = false;
                            this.facade.Focus = true;
                            this.topview_OnItemSelected(facade.ListLayout.ListItems[0], this.facade);
                            goto Label_05ED;

                        case 3:
                            this.mVidsCurrView = viewMode.Tag;
                            this.loadTags();
                            this.dbviewButton.Focus = false;
                            this.facade.Focus = true;
                            this.topview_OnItemSelected(facade.ListLayout.ListItems[0], this.facade);
                            goto Label_05ED;
                    }
                }
            }
            else if (control == this.btnPlaylist)
            {
                GUIWindowManager.ActivateWindow(0x1c);
            }
            else if ((control == this.facade) && (actionType == Action.ActionType.ACTION_ADD_TO_PLAYLIST))
            {
                if (!this.facade.SelectedListItem.IsFolder && (this.facade.SelectedListItem.Label != ".."))
                {
                    this.currPath = this.facade.SelectedListItem.Path.ToString();
                    if (!this.alwaysPlayAll)
                    {
                        g_Player.Play(this.facade.SelectedListItem.Path.ToString(), 0);
                    }
                    else
                    {
                      plp.GetPlaylist(PlayListType.PLAYLIST_MUSIC_VIDEO).Clear();
                        List<GUIListItem> items = new List<GUIListItem>();
                        items.AddRange(this.facade.ListLayout.ListItems.GetRange(this.facade.SelectedListItemIndex, this.facade.Count - this.facade.SelectedListItemIndex));
                        if (plp.GetPlaylist(PlayListType.PLAYLIST_MUSIC_VIDEO).Count == 0)
                        {
                            this.addToPlaylist(items, true);
                        }
                        else
                        {
                            this.addToPlaylist(items, false);
                        }
                    }
                }
                else if (!this.facade.SelectedListItem.IsFolder && (this.facade.SelectedListItem.Label == ".."))
                {
                    switch (this.mVidsCurrView)
                    {
                        case viewMode.Artists:
                            this.loadArtists();
                            this.facade.SelectedListItemIndex = this.lastItem;
                            goto Label_05ED;

                        case viewMode.Tag:
                            this.loadTags();
                            this.facade.SelectedListItemIndex = this.lastItem;
                            goto Label_05ED;

                        case viewMode.Top100:
                        case viewMode.Key:
                            goto Label_05ED;

                        case viewMode.Similar:
                        {
                            Settings settings = new Settings(Config.GetFolder(Config.Dir.Config) + "/MediaPortal.xml", true);
                            string lastView = settings.GetValue("mvid", "lastView");
                            string lastSubview = settings.GetValue("mvid", "lastSubview");
                            settings.Dispose();
                            this.setupLastView(lastView, lastSubview);
                            goto Label_05ED;
                        }
                    }
                }
                else if (this.facade.SelectedListItem.IsFolder && (this.mVidsCurrView == viewMode.Artists))
                {
                    this.lastItem = this.facade.SelectedListItemIndex;
                    this.setupArtistView(this.facade.SelectedListItem.Label);
                }
                else if (this.facade.SelectedListItem.IsFolder && (this.mVidsCurrView == viewMode.Tag))
                {
                    this.lastItem = this.facade.SelectedListItemIndex;
                    this.setupTagView(this.facade.SelectedListItem.Label);
                }
            }
        Label_05ED:
            base.OnClicked(controlId, control, actionType);
        }

        protected override void OnPageDestroy(int new_windowId)
        {
            Settings settings = new Settings(Config.GetFolder(Config.Dir.Config) + "/MediaPortal.xml", true);
            switch (this.mVidsCurrView)
            {
                case viewMode.Artists:
                    settings.SetValue("mvid", "lastView", "artist");
                    break;

                case viewMode.Tag:
                    settings.SetValue("mvid", "lastView", "tag");
                    break;

                case viewMode.Top100:
                    settings.SetValue("mvid", "lastView", "top100");
                    break;

                case viewMode.Key:
                    settings.SetValue("mvid", "lastView", "key");
                    break;
            }
            settings.Dispose();
            myLog.logger.log("disposing of fanart textures");
            foreach (string str in this.fanArtImages)
            {
                GUITextureManager.ReleaseTexture("[" + str + "]");
            }
            myLog.logger.log("done disposing");
            base.OnPageDestroy(new_windowId);
        }

        protected override void OnPageLoad()
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(this.updateStatistics), null);
            Settings settings = new Settings(Config.GetFolder(Config.Dir.Config) + "/MediaPortal.xml", true);
            string str = settings.GetValue("movies", "extensions");
            this.currPath = this.basePath;
            string lastView = settings.GetValue("mvid", "lastView");
            string lastSubview = settings.GetValue("mvid", "lastSubview");
            this.fanArtImages.Clear();
            this.setupLastView(lastView, lastSubview);
            settings.Dispose();
            if (!this.cycleViews)
            {
                this.dbviewButton.Label = "Change View";
            }
            if (g_Player.Playing && g_Player.IsVideo)
            {
                Log.Debug("Music Video DB - Currently Playing filename={0}", new object[] { g_Player.CurrentFile });
                foreach (GUIListItem item in this.facade.ListLayout.ListItems)
                {
                    if (item.Path == g_Player.CurrentFile)
                    {
                        this.facade.SelectedListItemIndex = this.facade.ListLayout.ListItems.IndexOf(item);
                        this.videoSelected_handler(item, this.facade);
                        break;
                    }
                }
            }
            base.OnPageLoad();
        }

        private void playRandomAll()
        {
            PlayList playlist = plp.GetPlaylist(PlayListType.PLAYLIST_MUSIC_VIDEO);;
            playlist.Clear();
            List<PlayListItem> list2 = this.db.getRandomPlaylist();
            foreach (PlayListItem item in list2)
            {
                playlist.Add(item);
            }
            this.plp.CurrentPlaylistType = PlayListType.PLAYLIST_MUSIC_VIDEO;
            playlist.Shuffle();
            this.plp.Play(0);
            GUIWindowManager.ActivateWindow(0x7d5);
        }

        private void playRandomArtist(string artist)
        {
            PlayListPlayer player = PlayListPlayer.SingletonPlayer;
            PlayList playlist = player.GetPlaylist(PlayListType.PLAYLIST_MUSIC_VIDEO);
            playlist.Clear();
            List<mVids.musicVideo> list2 = this.db.getFilesByArtist(artist);
            for (int i = 0; i < list2.Count; i++)
            {
                PlayListItem item = new PlayListItem();
                item.FileName =list2[i].Path;
                item.Type = PlayListItem.PlayListItemType.Video;
                item.Description =  list2[i].artist + " - " + list2[i].Label;
                playlist.Add(item);
            }
            player.CurrentPlaylistType = PlayListType.PLAYLIST_MUSIC_VIDEO;
            playlist.Shuffle();
            player.Play(0);
        }

        private void playRandomMenu()
        {
            GUIDialogMenu window = (GUIDialogMenu)GUIWindowManager.GetWindow(0x7dc);
            window.Reset();
            window.SetHeading("Choose Random Mode");
            window.Add("All");
            window.Add("Top 100");
            window.Add("By Artist");
            window.Add("By Tag");
            window.Add("Smart Random");
            window.DoModal(GUIWindowManager.ActiveWindow);
            string str3 = window.SelectedLabelText;
            if (str3 != null)
            {
                if (!(str3 == "All"))
                {
                    int count;
                    if (str3 == "By Artist")
                    {
                        List<string> list = this.db.getArtists();
                        window.Reset();
                        foreach (string str in list)
                        {
                            count = this.db.getFilesByArtist(str).Count;
                            if (count == 1)
                            {
                                window.Add(str + " (" + count.ToString() + " Video)");
                            }
                            else
                            {
                                window.Add(str + " (" + count.ToString() + " Videos)");
                            }
                        }
                        window.DoModal(GUIWindowManager.ActiveWindow);
                        if (window.SelectedLabelText != "")
                        {
                            this.playRandomArtist(list[window.SelectedLabel]);
                        }
                    }
                    else if (str3 == "Top 100")
                    {
                        this.playRandomTop100();
                    }
                    else if (str3 == "By Tag")
                    {
                        window.Reset();
                        window.ShowQuickNumbers = false;
                        List<string> list2 = this.db.getTags();
                        foreach (string str2 in list2)
                        {
                            count = this.db.getFilesByTag(str2).Count;
                            if (count == 1)
                            {
                                window.Add(str2 + " (" + count.ToString() + " Video)");
                            }
                            else
                            {
                                window.Add(str2 + " (" + count.ToString() + " Videos)");
                            }
                        }
                        window.DoModal(GUIWindowManager.ActiveWindow);
                        if (window.SelectedLabelText != "")
                        {
                            this.playRandomTag(window.SelectedLabelText);
                        }
                    }
                    else if (str3 == "Smart Random")
                    {
                        Randomness.smartRandom random = new Randomness.smartRandom();
                        Settings settings = new Settings(Config.GetFolder(Config.Dir.Config) + "/MediaPortal.xml", true);
                        int intNoPlay = settings.GetValueAsInt("mvid", "noPlayWeight", 6);
                        int intRecent = settings.GetValueAsInt("mvid", "recentWeight", 6);
                        int intTop = settings.GetValueAsInt("mvid", "topWeight", 6);
                        int totalVideosPercent = settings.GetValueAsInt("mvid", "totalPercent", 20);
                        int percentRecent = settings.GetValueAsInt("mvid", "recentPercent", 20);
                        int percentNoPlay = settings.GetValueAsInt("mvid", "noPlayPercent", 20);
                        int percentTop = settings.GetValueAsInt("mvid", "topPercent", 20);
                        List<mVids.musicVideo> items = random.getSmartRandom(this.db, intNoPlay, intRecent, intTop, percentRecent, percentTop, percentNoPlay, totalVideosPercent);
                        Log.Info("Music Video DB - Smart Random added {0} videos to the playlist", new object[] { items.Count.ToString() });
                        myLog.logger.log("added " + items.Count.ToString() + " vids");
                        this.addToPlaylist(items, true, true);
                        settings.Dispose();
                    }
                }
                else
                {
                    this.playRandomAll();
                }
            }
        }

        private void playRandomTag(string tag)
        {
            PlayListPlayer player = PlayListPlayer.SingletonPlayer;
            PlayList playlist = player.GetPlaylist(PlayListType.PLAYLIST_MUSIC_VIDEO);
            playlist.Clear();
            List<mVids.musicVideo> list2 = this.db.getFilesByTag(tag);
            for (int i = 0; i < list2.Count; i++)
            {
                PlayListItem item = new PlayListItem();
                item.FileName = list2[i].Path;
                item.Type = PlayListItem.PlayListItemType.Video;
                item.Description = list2[i].artist + " - " + list2[i].Label;
                playlist.Add(item);
            }
            player.CurrentPlaylistType = PlayListType.PLAYLIST_MUSIC_VIDEO;
            playlist.Shuffle();
            player.Play(0);
        }

        private void playRandomTop100()
        {
            PlayListPlayer player = PlayListPlayer.SingletonPlayer;
            PlayList playlist = player.GetPlaylist(PlayListType.PLAYLIST_MUSIC_VIDEO);
            playlist.Clear();
            List<mVids.musicVideo> list2 = this.db.getFilesByScore(100);
            for (int i = 0; i < list2.Count; i++)
            {
                PlayListItem item = new PlayListItem();
                item.FileName = list2[i].Path;
                item.Type = PlayListItem.PlayListItemType.Video;
                item.Description = list2[i].artist + " - " + list2[i].Label;
                playlist.Add(item);
            }
            player.CurrentPlaylistType = PlayListType.PLAYLIST_MUSIC_VIDEO;
            playlist.Shuffle();
            player.Play(0);
        }

        public string PluginName()
        {
            return "mVids";
        }

        private void rsWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            mVids.config config = new mVids.config();
            this.db.delMissing();
            config.updateDB();
            config.Dispose();
        }

        private void rsWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Log.Info("Music Video DB - Update Completed, refreshing control", new object[0]);
            if (GUIWindowManager.ActiveWindow == 0x19df)
            {
                this.OnPageLoad();
            }
        }

        private void setPlaybackInfo(object path)
        {
            try
            {
                if (this.db.fileInDB(path.ToString()))
                {
                    mVids.musicVideo video = this.db.getFileLabel(path.ToString());
                    Thread.Sleep(0x7d0);
                    path = path.ToString().Remove(0, path.ToString().LastIndexOf(@"\") + 1);
                    GUIPropertyManager.SetProperty("#Play.Current.Title", video.Label);
                    GUIPropertyManager.SetProperty("#Play.Current.Plot", this.db.getArtistInfo(video.artist).bioSummary);
                    GUIPropertyManager.SetProperty("#Play.Current.Thumb", this.thumbdir + @"\Artists\" + video.artist + ".jpg");
                }
            }
            catch (Exception exception)
            {
                Log.Error("Music Video DB - Error setting playback property information. error={0}", new object[] { exception.ToString() });
            }
        }

        private void setupArtistView(string artist)
        {
            this.mosaic.IsVisible = false;
            this.facade.Clear();
            GUIPropertyManager.SetProperty("#mvids.hierarchy", this.mVidsCurrView.ToString() + "  ->  " + artist);
            GUIListItem item = new GUIListItem();
            item.IsFolder = false;
            item.Label = "..";
            item.ThumbnailImage = this.thumbdir + @"\Artists\" + artist + ".jpg";
            item.Path = artist;
            item.OnItemSelected += new GUIListItem.ItemSelectedHandler(videoSelected_handler);
            Settings settings = new Settings(Config.GetFolder(Config.Dir.Config) + "/MediaPortal.xml", true);
            settings.SetValue("mvid", "lastSubview", artist);
            settings.Dispose();
            this.facade.Add(item);
            this.videos = this.db.getFilesByArtist(artist);
            if (!this.fanArtImages.Contains(artist))
            {
                this.fanArtImages.Clear();
                ThreadPool.QueueUserWorkItem(new WaitCallback(this.loadFanart), this.videos);
            }
            Log.Debug("Music Video DB - Returned {0} videos for {1}", new object[] { this.videos.Count.ToString(), artist });
            foreach (mVids.musicVideo video in this.videos)
            {
                video.ThumbnailImage = thumbdir + @"\Videos\" + video.Path.Remove(0, video.Path.LastIndexOf(@"\") + 1) + ".jpg";
                video.IconImage = thumbdir + @"\Videos\" + video.Path.Remove(0, video.Path.LastIndexOf(@"\") + 1) + ".jpg";

                video.IsFolder = false;
                video.OnItemSelected += new GUIListItem.ItemSelectedHandler(videoSelected_handler);
                this.facade.Add(video);
            }
            if (this.facade.Count > 0)
            {
                this.facade.SelectedListItemIndex = 1;
            }
        }

        private void setupKeyView()
        {
            this.mosaic.IsVisible = false;
            Settings settings = new Settings(Config.GetFolder(Config.Dir.Config) + "/MediaPortal.xml", true);
            settings.SetValue("mvid", "lastView", "key");
            settings.Dispose();
            this.facade.Clear();
            GUIPropertyManager.SetProperty("#mvids.hierarchy", "Most Recent");
            this.videos = this.db.getFilesByKeyOrder(100);
            ThreadPool.QueueUserWorkItem(new WaitCallback(this.loadFanart), this.videos);
            foreach (mVids.musicVideo video in this.videos)
            {
                video.ThumbnailImage = thumbdir + @"\Videos\" + video.Path.Remove(0, video.Path.LastIndexOf(@"\") + 1) + ".jpg";
                video.IconImage = thumbdir + @"\Videos\" + video.Path.Remove(0, video.Path.LastIndexOf(@"\") + 1) + ".jpg";
                video.IsFolder = false;
                video.OnItemSelected += new GUIListItem.ItemSelectedHandler(videoSelected_handler);
                this.facade.Add(video);
            }
            if (this.facade.Count > 0)
            {
              this.facade.SelectedListItemIndex = 0;
            }
        }

        private void setupLastView(string lastView, string lastSubview)
        {
            switch (lastView)
            {
                case "artist":
                    this.mVidsCurrView = viewMode.Artists;
                    this.dbviewButton.Label = "Artist View";
                    if (lastSubview == "root")
                    {
                        this.loadArtists();
                    }
                    else
                    {
                        this.setupArtistView(lastSubview);
                    }
                    return;

                case "top100":
                    this.mVidsCurrView = viewMode.Top100;
                    this.dbviewButton.Label = "Top 100";
                    this.setupTop100View();
                    return;

                case "key":
                    this.mVidsCurrView = viewMode.Key;
                    this.dbviewButton.Label = "Recent View";
                    this.setupKeyView();
                    return;

                case "tag":
                    this.mVidsCurrView = viewMode.Tag;
                    this.dbviewButton.Label = "Tag View";
                    if (lastSubview == "root")
                    {
                        this.loadTags();
                    }
                    else
                    {
                        this.setupTagView(lastSubview);
                    }
                    return;
            }
            this.mVidsCurrView = viewMode.Artists;
            this.dbviewButton.Label = "Artist View";
            if (this.facade.ListLayout.ListItems.Count == 0)
            {
                this.loadArtists();
            }
        }

        private void setupSimilarView(string artist)
        {
            this.mVidsCurrView = viewMode.Similar;
            this.facade.Clear();
            GUIPropertyManager.SetProperty("#mvids.hierarchy", artist + "  ->  Similar Videos");
            GUIListItem item = new GUIListItem();
            item.IsFolder = false;
            item.Label = "..";
            item.ThumbnailImage = thumbdir + @"\Artists\" + artist + ".jpg";
            item.Path = artist;
            item.OnItemSelected += new GUIListItem.ItemSelectedHandler(videoSelected_handler);
            this.facade.Add(item);
            try
            {
                this.videos = this.db.getSimilarVideos(artist);
            }
            catch
            {
            }
            Log.Debug("Music Video DB - Returned {0} similar videos for {1}", new object[] { this.videos.Count.ToString(), artist });
            foreach (mVids.musicVideo video in this.videos)
            {
                video.ThumbnailImage = thumbdir + @"\Videos\" + video.Path.Remove(0, video.Path.LastIndexOf(@"\") + 1) + ".jpg";
                video.IconImage = thumbdir + @"\Videos\" + video.Path.Remove(0, video.Path.LastIndexOf(@"\") + 1) + ".jpg";
                video.IsFolder = false;
                video.OnItemSelected += new GUIListItem.ItemSelectedHandler(videoSelected_handler);
                this.facade.Add(video);
            }
            if (this.facade.Count > 0)
            {
                this.facade.SelectedListItemIndex = 1;
            }
        }

        private void setupTagView(string tag)
        {
            this.mosaic.IsVisible = false;
            this.showStars(0);
            this.mosaic.IsVisible = false;
            Settings settings = new Settings(Config.GetFolder(Config.Dir.Config) + "/MediaPortal.xml", true);
            settings.SetValue("mvid", "lastSubview", tag);
            settings.Dispose();
            this.facade.Clear();
            GUIPropertyManager.SetProperty("#mvids.hierarchy", "Tags  ->  " + tag);
            GUIListItem item = new GUIListItem();
            item.IsFolder = false;
            item.Label = "..";
            item.MusicTag = tag;
            item.OnItemSelected += new GUIListItem.ItemSelectedHandler(videoSelected_handler);
            this.facade.Add(item);
            this.videos = this.db.getFilesByTag(tag);
            ThreadPool.QueueUserWorkItem(new WaitCallback(this.loadFanart), this.videos);
            foreach (mVids.musicVideo video in this.videos)
            {
                video.ThumbnailImage = thumbdir + @"\Videos\" + video.Path.Remove(0, video.Path.LastIndexOf(@"\") + 1) + ".jpg";
                video.IconImage = thumbdir + @"\Videos\" + video.Path.Remove(0, video.Path.LastIndexOf(@"\") + 1) + ".jpg";
                video.IsFolder = false;
                video.OnItemSelected += new GUIListItem.ItemSelectedHandler(videoSelected_handler);
                this.facade.Add(video);
            }
            if (this.facade.Count > 0)
            {
                this.facade.SelectedListItemIndex = 1;
            }
        }

        private void setupTop100View()
        {
            this.mosaic.IsVisible = false;
            this.facade.Clear();
            Settings settings = new Settings(Config.GetFolder(Config.Dir.Config) + "/MediaPortal.xml", true);
            settings.SetValue("mvid", "lastView", "top100");
            settings.Dispose();
            GUIPropertyManager.SetProperty("#mvids.hierarchy", "Top 100");
            this.videos = this.db.getFilesByScore(100);
            ThreadPool.QueueUserWorkItem(new WaitCallback(this.loadFanart), this.videos);
            Log.Debug("Music Video DB - Top 100 returned {0} videos", new object[] { this.videos.Count.ToString() });
            foreach (mVids.musicVideo video in this.videos)
            {
                video.ThumbnailImage = thumbdir + @"\Videos\" + video.Path.Remove(0, video.Path.LastIndexOf(@"\") + 1) + ".jpg";
                video.IconImage = thumbdir + @"\Videos\" + video.Path.Remove(0, video.Path.LastIndexOf(@"\") + 1) + ".jpg";
                video.IsFolder = false;
                video.OnItemSelected += new GUIListItem.ItemSelectedHandler(videoSelected_handler);
                this.facade.Add(video);
            }
            if (this.facade.Count > 0)
            {
                this.facade.SelectedListItemIndex = 0;
            }
        }

        public void ShowPlugin()
        {
            new mVids.config().ShowDialog();
        }

        private void showStars(int rating)
        {
            switch (rating)
            {
                case 0:
                    this.star1.IsVisible = false;
                    this.star2.IsVisible = false;
                    this.star3.IsVisible = false;
                    this.star4.IsVisible = false;
                    this.star5.IsVisible = false;
                    break;

                case 1:
                    this.star1.IsVisible = true;
                    this.star2.IsVisible = false;
                    this.star3.IsVisible = false;
                    this.star4.IsVisible = false;
                    this.star5.IsVisible = false;
                    break;

                case 2:
                    this.star1.IsVisible = true;
                    this.star2.IsVisible = true;
                    this.star3.IsVisible = false;
                    this.star4.IsVisible = false;
                    this.star5.IsVisible = false;
                    break;

                case 3:
                    this.star1.IsVisible = true;
                    this.star2.IsVisible = true;
                    this.star3.IsVisible = true;
                    this.star4.IsVisible = false;
                    this.star5.IsVisible = false;
                    break;

                case 4:
                    this.star1.IsVisible = true;
                    this.star2.IsVisible = true;
                    this.star3.IsVisible = true;
                    this.star4.IsVisible = true;
                    this.star5.IsVisible = false;
                    break;

                case 5:
                    this.star1.IsVisible = true;
                    this.star2.IsVisible = true;
                    this.star3.IsVisible = true;
                    this.star4.IsVisible = true;
                    this.star5.IsVisible = true;
                    break;
            }
        }

        private void topview_OnItemSelected(GUIListItem item, GUIControl parent)
        {
            if ((this.mVidsCurrView == viewMode.Artists) && (item != null))
            {
                try
                {
                    if (this.topLevelFanart)
                    {
                        this.displayFanart(item.Label);
                    }
                    GUIPropertyManager.SetProperty("#mvids.bio", item.TVTag.ToString());
                    GUIPropertyManager.SetProperty("#mvids.artist", item.Label);
                    GUIPropertyManager.SetProperty("#mvids.artim", item.ThumbnailImage);
                    GUIPropertyManager.SetProperty("#mvids.artvideocount", item.Duration.ToString());
                    GUIPropertyManager.SetProperty("#mvids.arttags", item.DVDLabel);
                    GUIPropertyManager.SetProperty("#mvids.artaveragerating", item.AlbumInfoTag.ToString());
                    GUIPropertyManager.Changed = true;
                }
                catch (Exception exception1)
                {
                    Exception exception = exception1;
                    Log.Info("Music Video DB - Error setting top-level information, error={0}", new object[] { exception.ToString() });
                }
            }
            else if ((this.mVidsCurrView == viewMode.Tag) && (item != null))
            {
                try
                {
                    List<string> list = new List<string>();
                    List<string> images = new List<string>();
                    string[] files = Directory.GetFiles(this.thumbdir + @"\Artists\");
                    GUIPropertyManager.SetProperty("#mvids.tag", item.Label);
                    list.AddRange(item.TVTag.ToString().Split(Environment.NewLine.ToCharArray()));
                    List<string> list3 = new List<string>();
                    list3.AddRange(files);
                    foreach (string str in list)
                    {
                        if (list3.Contains(this.thumbdir + @"\Artists\" + str + ".jpg") && (str != ""))
                        {
                            images.Add(this.thumbdir + @"\Artists\" + str + ".jpg");
                        }
                    }
                    Image image = new mVids.mosaicGenerator().getMosaic(images, new Rectangle(this.mosaic.XPosition, this.mosaic.YPosition, this.mosaic.Width, this.mosaic.Height), this.thumbdir, this.mosaicWidth, this.mosaicHeight);
                    string property = GUIPropertyManager.GetProperty("#mvids.mosaic");
                    string str3 = "[mosaic-" + item.Label + "]";
                    GUITextureManager.LoadFromMemory(image, str3, 0L, image.Width, image.Height);
                    GUIPropertyManager.SetProperty("#mvids.mosaic", str3);
                    Log.Debug("Music Video DB - Dropping texture [mosaic-" + property + "]", new object[0]);
                    GUITextureManager.ReleaseTexture("[mosaic-" + property + "]");
                }
                catch (Exception exception2)
                {
                    Log.Error("Music Video DB - Error generating mosaic:" + Environment.NewLine + exception2.ToString(), new object[0]);
                }
            }
        }

        private void updateStatistics(object obj)
        {
            int count = this.db.getFiles().Count;
            int num2 = this.db.getArtists().Count;
            mVids.musicVideo video = this.db.getFilesByScore(1)[0];
            GUIPropertyManager.SetProperty("#mvids.totalvideos", this.db.getFiles().Count + " videos total");
            GUIPropertyManager.SetProperty("#mvids.totalartists", this.db.getArtists().Count + " artists total");
            GUIPropertyManager.SetProperty("#mvids.favoritevideoname", video.Label);
            GUIPropertyManager.SetProperty("#mvids.favoritevideothumb", this.thumbdir + @"\Videos\" + video.Path.Remove(0, video.Path.LastIndexOf(@"\") + 1) + ".jpg");
            List<mVids.artist> list = this.db.getArtistsAndBios(true);
            foreach (mVids.artist artist in list)
            {
                artist.Rating= 0f;
            }
            foreach (mVids.musicVideo video2 in this.db.getFilesByScore(this.db.getFiles().Count))
            {
                foreach (mVids.artist artist in list)
                {
                    if (video2.artist == artist.artistName)
                    {
                        artist.Rating = artist.Rating + float.Parse(video2.score);
                        break;
                    }
                }
            }
            list.Sort((Comparison<mVids.artist>) ((a1, a2) => a2.Rating.CompareTo(a1.Rating)));
            GUIPropertyManager.SetProperty("#mvids.favoriteartistname", list[0].artistName);
            GUIPropertyManager.SetProperty("#mvids.favoriteartistthumb", this.thumbdir + @"\Artists\" + list[0].artistName + ".jpg");
        }

        private void updateTop100Order()
        {
            GUIListItem item = this.facade.SelectedListItem;
            this.setupTop100View();
            foreach (GUIListItem item2 in this.facade.ListLayout.ListItems)
            {
                if (item2.Path == item.Path)
                {
                    this.facade.SelectedListItemIndex = this.facade.ListLayout.ListItems.IndexOf(item2);
                }
            }
            this.videoSelected_handler(this.facade.SelectedListItem, this.facade);
        }

        private void videoSelected_handler(GUIListItem item, GUIControl parent)
        {
            try
            {
                GUIPropertyManager.SetProperty("#mvids.videoimage", item.ThumbnailImage);
                if (item.Label != "..")
                {
                    mVids.musicVideo video = new mVids.musicVideo();
                    if (this.facade.ListLayout.ListItems.Count > 0)
                    {
                        if (facade.ListLayout.ListItems[0].Label == "..")
                        {
                            video = this.videos[this.facade.ListLayout.ListItems.IndexOf(item) - 1];
                        }
                        else
                        {
                            video = this.videos[this.facade.ListLayout.ListItems.IndexOf(item)];
                        }
                        int num2 = (video.Duration / 0x3e8) / 60;
                        string str = num2.ToString();
                        num2 = (video.Duration / 0x3e8) % 60;
                        string str2 = num2.ToString();
                        string str3 = str + ":" + str2;
                        if (str3.Length == 3)
                        {
                            str3 = str3 + "0";
                        }
                        this.displayFanart(video.artist);
                        GUIPropertyManager.SetProperty("#mvids.artist", video.artist);
                        GUIPropertyManager.SetProperty("#mvids.bio", video.aI.bioContent);
                        GUIPropertyManager.SetProperty("#mvids.artim", this.thumbdir + @"\Artists\" + video.artist + ".jpg");
                        if (((this.mVidsCurrView == viewMode.Tag) | (this.mVidsCurrView == viewMode.Top100)) | (this.mVidsCurrView == viewMode.Key))
                        {
                            GUIPropertyManager.SetProperty("#mvids.videotitle", video.Label.Remove(0, video.Label.IndexOf("- ") + 2).Trim());
                        }
                        else
                        {
                            GUIPropertyManager.SetProperty("#mvids.videotitle", video.Label);
                        }
                        GUIPropertyManager.SetProperty("#mvids.videolength", str3);
                        GUIPropertyManager.SetProperty("#mvids.videoplaycount", video.playcount);
                        GUIPropertyManager.SetProperty("#mvids.videoscore", video.score);
                        GUIPropertyManager.SetProperty("#mvids.videorank", video.ranking);
                        GUIPropertyManager.SetProperty("#mvids.arttags", video.tags);
                        GUIPropertyManager.SetProperty("#mvids.videoscore", (int.Parse(video.rating) * int.Parse(video.playcount)).ToString());
                        this.showStars(int.Parse(video.rating));
                    }
                }
                else
                {
                    GUIPropertyManager.SetProperty("#mvids.artist", item.Path);
                    GUIPropertyManager.SetProperty("#mvids.videotitle", "..");
                    GUIPropertyManager.SetProperty("#mvids.videolength", "");
                    GUIPropertyManager.SetProperty("#mvids.videoplaycount", "");
                    GUIPropertyManager.SetProperty("#mvids.videoscore", "");
                    GUIPropertyManager.SetProperty("#mvids.videorank", "");
                    int num = 0;
                    foreach (mVids.musicVideo video2 in this.videos)
                    {
                        num += int.Parse(video2.rating);
                    }
                    if ((this.videos.Count != 0) && (num != 0))
                    {
                        this.showStars(Convert.ToInt32((int) (num / this.videos.Count)));
                    }
                }
            }
            catch (Exception exception)
            {
                Log.Error("Music Video DB - Error setting property fields for video", new object[0]);
                Log.Error(exception.ToString(), new object[0]);
            }
        }

        private void watcher_Created(object sender, FileSystemEventArgs e)
        {
            Log.Info("Music Video DB - Change in watched directory - Created: {0}", new object[] { e.Name });
            foreach (string str in this.exts)
            {
                if (e.Name.EndsWith(str))
                {
                    this.db.addSingleFile(e.FullPath);
                    Log.Info("Music Video DB - Update Completed, refreshing window", new object[0]);
                    if (GUIWindowManager.ActiveWindow == 0x19df)
                    {
                        this.OnPageLoad();
                    }
                    return;
                }
            }
            Log.Info("Music Video DB - Object created does not have an extension we care about", new object[0]);
        }

        private void watcher_Deleted(object sender, FileSystemEventArgs e)
        {
            Log.Info("Music Video DB - Change in watched directory", new object[0]);
            foreach (string str in this.exts)
            {
                if (e.Name.Contains(str))
                {
                    int num = this.db.delMissing();
                    try
                    {
                        if (File.Exists(this.thumbdir + @"\Videos\" + e.Name + ".jpg"))
                        {
                            File.Delete(this.thumbdir + @"\Videos\" + e.Name + ".jpg");
                        }
                        Log.Info("Music Video DB - Deleted associated thumb {0}", new object[] { this.thumbdir + @"\Videos\" + e.Name + ".jpg" });
                    }
                    catch (Exception exception)
                    {
                        Log.Error("Music Video DB - Error deleting thumbnail " + this.thumbdir + @"\Videos\" + e.Name + ".jpg, error=" + exception.ToString(), new object[0]);
                    }
                    Log.Info("Music Video DB - Removed reference and thumbnail for {0} file(s)", new object[] { num.ToString() });
                    Log.Info("Music Video DB - Update Completed, refreshing window", new object[0]);
                    if (GUIWindowManager.ActiveWindow == 0x19df)
                    {
                        this.OnPageLoad();
                    }
                    return;
                }
            }
            Log.Info("Music Video DB - Object deleted does not have an extension we care about", new object[0]);
        }

        private void watcher_Renamed(object sender, RenamedEventArgs e)
        {
            Log.Info("Music Video DB - Change in watched directory", new object[0]);
            foreach (string str in this.exts)
            {
                if (e.Name.Contains(str))
                {
                    this.db.removeSingle(e.OldFullPath);
                    this.db.addSingleFile(e.FullPath);
                    Log.Info("Music Video DB - Update Completed, refreshing window", new object[0]);
                    if (GUIWindowManager.ActiveWindow == 0x19df)
                    {
                        this.OnPageLoad();
                    }
                    return;
                }
            }
            Log.Info("Music Video DB - Object renamed does not have extension we care about", new object[0]);
        }

        public override int GetID
        {
            get
            {
                return 0x19df;
            }
            set
            {
            }
        }

        private enum viewMode
        {
            Shares,
            Artists,
            Tag,
            Top100,
            Key,
            Similar
        }
    }
}

